
<template>
  <BhTable
      title="职级管理"
      row-key="id"
      v-model:selected-keys="selectedKeys"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :data="dataList as []"
      :columns="columns"
      @refresh="search"
      :loading="loading"
      :pagination="pagination"
      :row-selection="rowSelection"
      :disabled-tools="['size']"
      :disabled-column-keys="['name']"
  >
    <template #top>
      <BhForm  ref="formRef" :columns="queryColumns" :model-value="queryForm"
               :options="options" @search="search" @reset="reset"></BhForm>
    </template>
    <template #toolbar-left>
      <a-space>
        <a-button
            v-permission="['sys:level:add']"
            type="primary"
            @click="emits('openAdd')"
        >
          <template #icon>
            <icon-plus/>
          </template>
          {{ $t('common.create') }}
        </a-button>
        <a-button
            v-permission="['sys:level:delete']"
            type="primary"
            status="danger"
            :disabled="selectedKeys.length === 0"
            @click="deleteSelectRows"
        >
          <template #icon>
            <icon-delete/>
          </template>
          {{ $t('common.delete') }}
        </a-button>
      </a-space>
    </template>

    <template #status="{ record }">
      <!-- 有修改权限 -->
      <a-switch
          v-if="hasPermission('sys:level:status')"
          v-model="record.status"
          type="round"
          :checked-text="TableSwitchStatusText.checkedText"
          :unchecked-text="TableSwitchStatusText.uncheckedText"
          :checked-value="TableSwitchStatus.ENABLED"
          :unchecked-value="TableSwitchStatus.DISABLED"
          :before-change="(s: number) => updateStatus(record.id, s)"
      />
      <a-badge
          v-else
          :status="record.status == TableSwitchStatus.ENABLED ? 'processing' : 'danger'"
          :text="record.status == TableSwitchStatus.DISABLED ? '开启' : '关闭'"
      />
    </template>
    <!-- 操作 -->
    <template #handle="{ record }">
      <!-- 修改 -->
      <a-button
          v-permission="['sys:level:edit']"
          type="text"
          size="mini"
          @click="emits('openUpdate', record)"
      >
        修改
      </a-button>
      <!-- 删除 -->
      <a-button
          v-permission="['sys:level:delete']"
          type="text"
          size="mini"
          status="danger"
          @click="deleteRow(record)"
          :disabled="record.code === AdminRoleCode"
      >
        删除
      </a-button>
    </template>

  </BhTable>

</template>
<script setup lang="ts">
import {useTable} from '@/hooks/modules/useTable';
import {useLoading} from '@/hooks/modules/useLoading';
import {type QueryRequest, getList,type QueryResponse,deleteRows, updateRowStatus,batchDeleteRows} from '@/api/system/level';
import type {TableInstanceColumns} from '@/components/BhTable'
import {Message} from "@arco-design/web-vue";
import {isMobile} from '@/utils'
import {AdminRoleCode, TableSwitchStatus, TableSwitchStatusText} from "@/types/const";
import usePermission from '@/hooks/permission';
import { type Columns, BhForm, type Options } from '@/components/BhForm'

const {setLoading} = useLoading();
const {hasPermission} = usePermission();

const options: Options = {
  form: { layout: 'inline' },
  grid: { cols: { xs: 1, sm: 1, md: 2, lg: 3, xl: 3, xxl: 2 } },
  fold: { enable: false, index: 1, defaultCollapsed: true },
}
const queryForm = reactive<QueryRequest>({
  name: '',
});

const queryColumns: Columns = reactive([
  {
    label: '职级名称',
    field: 'name',
    type: 'input',
    props: {
      placeholder: '请输入职级名称',
    }
  },
])
const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete,
  selectedKeys,
  rowSelection
} = useTable((page) => getList({...queryForm, ...page}), {
  immediate: true,
});
const columns: TableInstanceColumns[] = [
  {title: '序号',width: 66,dataIndex: 'id',align: 'center'},
  {title: '职级名称', dataIndex: 'name', slotName: 'name', align: 'center', ellipsis: true, tooltip: true},
  {title: '状态', dataIndex: 'status', slotName: 'status', align: 'center', width: 120, ellipsis: true, tooltip: true},
  {title: '排序', dataIndex: 'sort', align: 'center', show: true, ellipsis: true, tooltip: true},
  {title: '创建时间', dataIndex: 'create_time', align: 'center', width: 180},
  {title: '更新时间', dataIndex: 'update_time', align: 'center', width: 180},
  {title: '操作', dataIndex: 'handle',slotName: 'handle', width: 200,align: 'center',fixed: !isMobile() ? 'right' : undefined},
]
//重置搜索
const reset = () => {
  queryForm.name = undefined
  search()
}
// 批量删除
const deleteSelectRows = async () => {
  if (selectedKeys.value.length <= 0) {
    Message.error('请选择数据');
  }
  try {
    setLoading(true);
    // 调用删除接口
    await batchDeleteRows(selectedKeys.value as number[]);
    Message.success(`成功删除 ${selectedKeys.value.length} 条数据`);
    selectedKeys.value = [];
    // 重新加载数据
    reset()
  } catch (e) {
    setLoading(false);
  } finally {
    setLoading(false);
  }
};
const emits = defineEmits(['openAdd', 'openUpdate', 'openGrantRole']);


// 更新状态
const updateStatus = (id: number, status: number) => {
  return updateRowStatus({
    id,
    status,
  }).then(() => {
    Message.success('操作成功');
  });
};

// 删除数据
const deleteRow = (record: QueryResponse) => {
  return handleDelete(() => deleteRows(record.id), {
    content: `是否确定删除职级「${record.name}」？`,
    showModal: true,
  })
}

// 新增编辑后回调
const restartCallback = () => {
  reset();
};

defineExpose({
  restartCallback,
});
</script>
<style scoped lang="less"></style>
